<template>
  <div class="channel-quality">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>渠道数据质量分析</span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
              style="width: 240px"
            />
            <el-button type="primary" @click="handleExport" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出报告
            </el-button>
          </div>
        </div>
      </template>

      <!-- 质量指标概览 -->
      <el-row :gutter="20" class="quality-overview">
        <el-col :xs="24" :sm="12" :md="6">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">总推送量</span>
              <el-icon size="24" color="#409EFF">
                <TrendCharts />
              </el-icon>
            </div>
            <div class="metric-value">{{ overviewData.totalPushes }}</div>
            <div class="metric-change">
              <span :class="overviewData.pushesChange >= 0 ? 'text-success' : 'text-danger'">
                <el-icon>
                  <CaretTop v-if="overviewData.pushesChange >= 0" />
                  <CaretBottom v-else />
                </el-icon>
                {{ Math.abs(overviewData.pushesChange) }}%
              </span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">成功率</span>
              <el-icon size="24" color="#67C23A">
                <SuccessFilled />
              </el-icon>
            </div>
            <div class="metric-value">{{ overviewData.avgSuccessRate }}%</div>
            <div class="metric-change">
              <span :class="overviewData.successRateChange >= 0 ? 'text-success' : 'text-danger'">
                <el-icon>
                  <CaretTop v-if="overviewData.successRateChange >= 0" />
                  <CaretBottom v-else />
                </el-icon>
                {{ Math.abs(overviewData.successRateChange) }}%
              </span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">平均响应时间</span>
              <el-icon size="24" color="#E6A23C">
                <Clock />
              </el-icon>
            </div>
            <div class="metric-value">{{ overviewData.avgResponseTime }}ms</div>
            <div class="metric-change">
              <span :class="overviewData.responseTimeChange <= 0 ? 'text-success' : 'text-danger'">
                <el-icon>
                  <CaretTop v-if="overviewData.responseTimeChange > 0" />
                  <CaretBottom v-else />
                </el-icon>
                {{ Math.abs(overviewData.responseTimeChange) }}%
              </span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">渠道数量</span>
              <el-icon size="24" color="#909399">
                <OfficeBuilding />
              </el-icon>
            </div>
            <div class="metric-value">{{ overviewData.channelCount }}</div>
            <div class="metric-change">
              <span :class="overviewData.channelCountChange >= 0 ? 'text-success' : 'text-danger'">
                <el-icon>
                  <CaretTop v-if="overviewData.channelCountChange >= 0" />
                  <CaretBottom v-else />
                </el-icon>
                {{ Math.abs(overviewData.channelCountChange) }}
              </span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-section">
        <el-col :xs="24" :lg="12">
          <el-card>
            <template #header>
              <span>渠道成功率趋势</span>
            </template>
            <div ref="successRateChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card>
            <template #header>
              <span>渠道响应时间分布</span>
            </template>
            <div ref="responseTimeChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-section">
        <el-col :xs="24" :lg="12">
          <el-card>
            <template #header>
              <span>渠道推送量对比</span>
            </template>
            <div ref="pushVolumeChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card>
            <template #header>
              <span>渠道质量评分</span>
            </template>
            <div ref="qualityScoreChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据表格 -->
      <el-card class="detail-table">
        <template #header>
          <span>渠道详细数据</span>
          <div class="table-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索渠道名称"
              clearable
              style="width: 200px"
              @input="handleSearch"
            />
          </div>
        </template>
        
        <el-table
          :data="filteredTableData"
          border
          stripe
          style="width: 100%"
          :default-sort="{ prop: 'successRate', order: 'descending' }"
        >
          <el-table-column prop="channelName" label="渠道名称" min-width="150" />
          <el-table-column prop="channelType" label="渠道类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getChannelTypeTag(row.channelType)" size="small">
                {{ getChannelTypeLabel(row.channelType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalPushes" label="总推送量" width="100" sortable />
          <el-table-column prop="successfulPushes" label="成功量" width="100" sortable />
          <el-table-column prop="failedPushes" label="失败量" width="100" sortable />
          <el-table-column prop="successRate" label="成功率" width="120" sortable>
            <template #default="{ row }">
              <span :class="getSuccessRateClass(row.successRate)">
                {{ row.successRate }}%
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="avgResponseTime" label="平均响应时间(ms)" width="150" sortable />
          <el-table-column prop="maxResponseTime" label="最大响应时间(ms)" width="150" sortable />
          <el-table-column prop="minResponseTime" label="最小响应时间(ms)" width="150" sortable />
          <el-table-column label="质量评级" width="100" fixed="right">
            <template #default="{ row }">
              <el-tag :type="getQualityRatingType(row.successRate)" size="small">
                {{ getQualityRating(row.successRate) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getChannelQualityAnalysis } from '@/api/channel'
import type { ChannelQualityData } from '@/api/channel'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const dateRange = ref<string[]>([])
const searchText = ref('')
const tableData = ref<ChannelQualityData[]>([])
const overviewData = reactive({
  totalPushes: 0,
  avgSuccessRate: 0,
  avgResponseTime: 0,
  channelCount: 0,
  pushesChange: 0,
  successRateChange: 0,
  responseTimeChange: 0,
  channelCountChange: 0
})

// 图表实例
let successRateChart: echarts.ECharts | null = null
let responseTimeChart: echarts.ECharts | null = null
let pushVolumeChart: echarts.ECharts | null = null
let qualityScoreChart: echarts.ECharts | null = null

// DOM引用
const successRateChartRef = ref<HTMLElement>()
const responseTimeChartRef = ref<HTMLElement>()
const pushVolumeChartRef = ref<HTMLElement>()
const qualityScoreChartRef = ref<HTMLElement>()

// 计算属性 - 过滤后的表格数据
const filteredTableData = computed(() => {
  if (!searchText.value) return tableData.value
  return tableData.value.filter(item => 
    item.channelName.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 初始化日期范围（最近30天）
const initDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 30)
  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]
}

// 获取质量分析数据
const fetchQualityAnalysis = async () => {
  loading.value = true
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    const { data } = await getChannelQualityAnalysis(params)
    tableData.value = data.channels
    
    // 更新概览数据
    overviewData.totalPushes = data.overview.totalPushes
    overviewData.avgSuccessRate = data.overview.avgSuccessRate
    overviewData.avgResponseTime = data.overview.avgResponseTime
    overviewData.channelCount = data.overview.channelCount
    overviewData.pushesChange = data.overview.pushesChange
    overviewData.successRateChange = data.overview.successRateChange
    overviewData.responseTimeChange = data.overview.responseTimeChange
    overviewData.channelCountChange = data.overview.channelCountChange
    
    // 初始化图表
    setTimeout(() => {
      initCharts(data)
    }, 100)
  } catch (error) {
    ElMessage.error('获取质量分析数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = (data: any) => {
  // 成功率趋势图
  if (successRateChartRef.value) {
    successRateChart = echarts.init(successRateChartRef.value)
    const successRateOption = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c}%'
      },
      legend: {
        data: ['成功率']
      },
      xAxis: {
        type: 'category',
        data: data.trendDates || [],
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [{
        name: '成功率',
        type: 'line',
        data: data.successRateTrend || [],
        smooth: true,
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
          ])
        }
      }]
    }
    successRateChart.setOption(successRateOption)
  }

  // 响应时间分布图
  if (responseTimeChartRef.value) {
    responseTimeChart = echarts.init(responseTimeChartRef.value)
    const responseTimeOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        name: '响应时间分布',
        type: 'pie',
        radius: '50%',
        data: data.responseTimeDistribution || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    responseTimeChart.setOption(responseTimeOption)
  }

  // 推送量对比图
  if (pushVolumeChartRef.value) {
    pushVolumeChart = echarts.init(pushVolumeChartRef.value)
    const pushVolumeOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['成功推送', '失败推送']
      },
      xAxis: {
        type: 'category',
        data: data.channels?.map((c: ChannelQualityData) => c.channelName) || [],
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '成功推送',
          type: 'bar',
          data: data.channels?.map((c: ChannelQualityData) => c.successfulPushes) || [],
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '失败推送',
          type: 'bar',
          data: data.channels?.map((c: ChannelQualityData) => c.failedPushes) || [],
          itemStyle: {
            color: '#F56C6C'
          }
        }
      ]
    }
    pushVolumeChart.setOption(pushVolumeOption)
  }

  // 质量评分图
  if (qualityScoreChartRef.value) {
    qualityScoreChart = echarts.init(qualityScoreChartRef.value)
    const qualityScoreOption = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c}分'
      },
      radar: {
        indicator: [
          { name: '成功率', max: 100 },
          { name: '稳定性', max: 100 },
          { name: '响应速度', max: 100 },
          { name: '可靠性', max: 100 },
          { name: '可用性', max: 100 }
        ]
      },
      series: [{
        name: '渠道质量评分',
        type: 'radar',
        data: data.channels?.map((c: ChannelQualityData) => ({
          value: [
            c.successRate,
            Math.max(0, 100 - c.successRate), // 稳定性
            Math.max(0, 100 - c.avgResponseTime / 10), // 响应速度
            c.successRate * 0.8, // 可靠性
            c.successRate * 0.9 // 可用性
          ],
          name: c.channelName
        })) || []
      }]
    }
    qualityScoreChart.setOption(qualityScoreOption)
  }
}

// 日期范围改变
const handleDateChange = () => {
  fetchQualityAnalysis()
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
}

// 导出报告
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 这里需要实现导出功能
    ElMessage.success('报告导出成功')
  } catch (error) {
    ElMessage.error('报告导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 工具函数
const getChannelTypeTag = (type: string) => {
  const tagTypes: Record<string, string> = {
    upstream: 'info',
    downstream: 'success',
    bank: 'primary',
    consumer_finance: 'warning',
    small_loan: 'danger'
  }
  return tagTypes[type] || 'info'
}

const getChannelTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    upstream: '上游渠道',
    downstream: '下游渠道',
    bank: '银行',
    consumer_finance: '消费金融',
    small_loan: '小贷公司'
  }
  return labels[type] || type
}

const getSuccessRateClass = (rate: number) => {
  if (rate >= 90) return 'text-success'
  if (rate >= 70) return 'text-warning'
  return 'text-danger'
}

const getQualityRating = (rate: number) => {
  if (rate >= 95) return '优秀'
  if (rate >= 90) return '良好'
  if (rate >= 80) return '一般'
  if (rate >= 70) return '较差'
  return '差'
}

const getQualityRatingType = (rate: number) => {
  if (rate >= 95) return 'success'
  if (rate >= 90) return 'info'
  if (rate >= 80) return 'warning'
  return 'danger'
}

// 窗口大小改变时重新渲染图表
const handleResize = () => {
  successRateChart?.resize()
  responseTimeChart?.resize()
  pushVolumeChart?.resize()
  qualityScoreChart?.resize()
}

// 生命周期
onMounted(() => {
  initDateRange()
  fetchQualityAnalysis()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  successRateChart?.dispose()
  responseTimeChart?.dispose()
  pushVolumeChart?.dispose()
  qualityScoreChart?.dispose()
})
</script>

<style scoped>
.channel-quality {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 质量概览 */
.quality-overview {
  margin-bottom: 30px;
}

.metric-card {
  padding: 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  height: 100%;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.metric-title {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #212529;
  margin-bottom: 10px;
}

.metric-change {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.change-label {
  color: #6c757d;
}

/* 图表区域 */
.chart-section {
  margin-bottom: 20px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

/* 详细数据表格 */
.detail-table {
  margin-top: 20px;
}

.table-actions {
  display: flex;
  gap: 10px;
}

/* 文本颜色 */
.text-success {
  color: #28a745;
}

.text-danger {
  color: #dc3545;
}

.text-warning {
  color: #ffc107;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .channel-quality {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .metric-value {
    font-size: 24px;
  }
  
  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .metric-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .chart-container {
    height: 200px;
  }
}
</style>